package com.mxsoft.web;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 模拟高并发
 *
 * @author zhangyingxuan
 */
public class SimulateHighConcurrency2 {
    //请求总数
    public static int clientTotal = 100000;

    //同时并发执行的线程数
    public static int threadTotal = 20;

    private static AtomicInteger num = new AtomicInteger();

    public static volatile int successNum = 0;
    public static volatile int failNum = 0;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(1000);
        //信号量, 此处用于控制并发的线程数
        final Semaphore semaphore = new Semaphore(threadTotal);

        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for(int i = 0; i < clientTotal; i ++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    String doneWork = TestDemo.doneWork();
                    if (doneWork.contains("success")) {
                        successNum++;
                    } else {
                        System.out.println(doneWork);
                        failNum++;
                    }
                    semaphore.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
                System.out.println(num.incrementAndGet());
            });
        }

        countDownLatch.await();

        executorService.shutdown();

        System.out.println("successNum: " + successNum + " failNum: " + failNum);
    }
}
